import sys
import datetime
from PyQt4 import QtCore, QtGui


sys.path.append("UI")
import os
home = os.getcwd()
os.chdir("UI")
os.system('python Builder.py')
os.chdir(home)

VERSION = '001ALPHA'

import People
import Events
import PeopleOnEvents
import TripExpenses
import SubGroupExpenses
import PeopleInSubGroup
import MySQL
import DataBase


#from UI import *
from UI.CreateNewEventDiag import Ui_CreateNewEventDiag
from UI.MainGui import Ui_MainWindow
#from UI.AddPersonDiag import Ui_AddPersonDiag
from UI.AdminUserDetailsDiag import Ui_AdminUserDetailsDiag
from UI.SignInDiag import Ui_SignInDiag
from UI.UserDetailsDiag import Ui_UserDetailsDiag
from UI.ConfirmDiag import Ui_ConfirmDiag
from UI.EditEventDiag import Ui_EditEventDiag
from UI.AddPersonToEventDiag import Ui_AddPersonToEventDiag
from UI.SelectEventDiag import Ui_SelectEventDiag
from UI.SelectEventDiagAdmin import Ui_SelectEventDiagAdmin
from UI.EventDatesSelectDiag import Ui_EventDatesSelectDiag
#from EventDatesSelectDiagAdmin import Ui_EventDatesSelectDiagAdmin
from UI.AddTripExpenseDiag import Ui_AddTripExpenseDiag
from UI.ViewTripExpenseDiag import Ui_ViewTripExpenseDiag
from UI.EditTripExpenseDiag import Ui_EditTripExpenseDiag
from UI.AddSubGroupExpenseDiag import Ui_AddSubGroupExpenseDiag
from UI.AddPersonToSubGroupDiag import Ui_AddPersonToSubGroupDiag
from UI.ViewSubGroupExpenseDiag import Ui_ViewSubGroupExpenseDiag
from UI.ViewExpenseSummaryDiag import Ui_ViewExpenseSummaryDiag


class ConfirmDiag(QtGui.QDialog, Ui_ConfirmDiag):
    def __init__(self, Message):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.label.setText(Message)
        self.ID = 0

class SelectEvent(QtGui.QDialog, Ui_SelectEventDiag):
    def __init__(self, EventList):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        for Item in EventList:
            self.listWidget.addItem(Item)
        self.listWidget.setCurrentRow(0)
        
class SelectEventAdmin(QtGui.QDialog, Ui_SelectEventDiagAdmin):
    def __init__(self, EventList):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        for Item in EventList:
            self.listWidget.addItem(Item)
        self.listWidget.setCurrentRow(0)
    
        self.connect(self.CreateNewEventButton, QtCore.SIGNAL("clicked()"), self.AddNewEvent)
        
        
    def AddNewEvent(self):
        self.emit(QtCore.SIGNAL('NewEvent()'))

class AddPersonToSubGroup(QtGui.QDialog, Ui_AddPersonToSubGroupDiag):
    def __init__(self, People):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.People = People
        
        self.PopulateTable()
        
    def PopulateTable(self):
        for Person in self.People:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Person.PID))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 2, QtGui.QCheckBox())
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setTristate(False)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setCheckState(0)
            i = 0
            while (i < self.tableWidget.columnCount()):
                self.tableWidget.resizeColumnToContents(i)
                i = i + 1
                
    def GetAddedPeople(self):
        PIDS = []
        while self.tableWidget.rowCount() != 0:
            if self.tableWidget.cellWidget(0, 2).checkState() == 2:
                PIDS.append(int(self.tableWidget.item(0,0).text()))
            self.tableWidget.removeRow(0)
        return PIDS

class AddSubGroupExpense(QtGui.QDialog, Ui_AddSubGroupExpenseDiag):
    def __init__(self, People, Expense = '', PeopleInExpense = []):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.PeopleOnEvent = People
        self.Amount = '$0.0'
        
        self.AddedPIDs=PeopleInExpense
        
        self.Expense = Expense
        if Expense != '':
            self.SgExp_id = Expense.SgExp_id
            self.ExpenseAmount.setText("""$%.2f"""%Expense.Amount)
            self.Amount = """$%.2f"""%Expense.Amount
            Desc = Expense.Desc.split('\n\n')
            self.ExpenseTitle.setText(Desc[0])
            self.ExpenseDesc.setPlainText(Desc[-1])
            
        self.connect(self.DoneButton, QtCore.SIGNAL("clicked()"), self.Finished)
        self.connect(self.ExpenseAmount, QtCore.SIGNAL("editingFinished()"), self.CheckAmount)
        self.connect(self.AddPersonButton, QtCore.SIGNAL("clicked()"), self.AddPerson)
        self.ExpenseAmount.setText(self.Amount)
        
        self.PopulateTable()
        
    
    def CheckAmount(self):
        Number, FloatCheck = self.ExpenseAmount.text().replace('$','').toFloat()
        if not FloatCheck:
            self.ExpenseAmount.setText(self.Amount)
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Input must be of type float")
            self.Message.show()
        else:
            if '$' not in self.ExpenseAmount.text():
                text = '$' + self.ExpenseAmount.text()
                self.ExpenseAmount.setText(text)
                self.Amount = text
        self.PopulateTable()
        
        
    def CheckExpenseTitle(self):
        Res = False
        if self.ExpenseTitle.text() != "":
            Res = True
        return Res
        
    def Finished(self):
        if self.CheckExpenseTitle():
            self.accept()
        else:
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Please enter an expense name")
            self.Message.show()
    
    def AddPerson(self):
        NewPeople  = []
        for PID in self.PeopleOnEvent.keys():
            if PID not in self.AddedPIDs:
                NewPeople.append(self.PeopleOnEvent[PID])   
        self.AddPersonDiag = AddPersonToSubGroup(NewPeople)
        self.AddPersonDiag.show()
        self.connect(self.AddPersonDiag, QtCore.SIGNAL("accepted()"), self.AddPeopleSelect)
        
    def AddPeopleSelect(self):
        self.AddedPIDs = self.AddedPIDs + self.AddPersonDiag.GetAddedPeople()
        self.PopulateTable()
             
    def PopulateTable(self):
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        for PID in self.AddedPIDs:
            Person = self.PeopleOnEvent[PID]
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Person.PID))
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))
            
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 2, QtGui.QTableWidgetItem("""%.2f"""%(100.0/len(self.AddedPIDs))))
            #self.connect( self.tableWidget.item(self.tableWidget.rowCount()-1, 2), QtCore.SIGNAL("editingFinished()"), self.UpdateAmount)
            
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 3, QtGui.QTableWidgetItem("""%.2f"""%(float(self.ExpenseAmount.text().replace('$',''))*(1.0/len(self.AddedPIDs)))))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 4, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 4).uniqueId = """%d"""%Person.PID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 4).clicked.connect(self.OnDeletePerson)

            i = 0
            while (i < self.tableWidget.columnCount()):
                self.tableWidget.resizeColumnToContents(i)
                i = i + 1
    #def UpdateAmount(self):
    #    print 'UpdateAmount'
    #

    def OnDeletePerson(self):
        button =  self.sender()
        print int(button.uniqueId)
        self.AddedPIDs.remove(int(button.uniqueId))
        self.PopulateTable()
        
    def GetPIDSOfPeopleOnEvent(self):
        People = []
        while self.tableWidget.rowCount() != 0:
            People.append([int(self.tableWidget.item(0,0).text()), float(self.tableWidget.item(0,2).text())])
            self.tableWidget.removeRow(0)
        return People
    
    def getDate(self):
        return datetime.date(self.ExpenseDate.date().year(),
                                self.ExpenseDate.date().month(),
                                self.ExpenseDate.date().day())
        
    def getAmount(self):
        return float(self.ExpenseAmount.text().replace('$',''))
        
    def getDesc(self):
        return self.ExpenseTitle.text() + '\n\n' + self.ExpenseDesc.toPlainText()
        
    def GetExpenseObj(self):
        self.Expense.Amount = float(self.ExpenseAmount.text().replace('$',''))
        self.Expense.Desc = self.ExpenseTitle.text() + '\n\n' + self.ExpenseDesc.toPlainText()
        return self.Expense        
     
class ViewSubGroupExpense(QtGui.QDialog, Ui_ViewSubGroupExpenseDiag):
    def __init__(self, SubGroupExpenses, PeopeInSubGroup, PeopleOnEvent, EventId):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.PeopeInSubGroup = PeopeInSubGroup
        self.SubGroupExpenses = SubGroupExpenses
        self.People = PeopleOnEvent
        self.EventId = EventId
        self.PopulateTable()
        
    def PopulateTable(self):
        
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        
        Expenses = self.SubGroupExpenses.GetSubGroupExpenses(EID = self.EventId)
        People = self.People
        for Expense in Expenses:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            #self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Expense.SgExp_id))
            
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%d/%d/%d"""%(Expense.Date.day, Expense.Date.month, Expense.Date.year)))
            
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 2, QtGui.QTableWidgetItem("""%s"""%Expense.Desc.split("\n\n")[0]))
            
            Person = People[Expense.PID]
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 3, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))

            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 4, QtGui.QTableWidgetItem("""$%.2f"""%Expense.Amount))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 5, QtGui.QComboBox())
            PIDsInGroup = self.PeopeInSubGroup.GetAllPeopleInSubgroupOnEvent(Expense.SgExp_id, self.EventId)
            for PID, Prop in PIDsInGroup:
                Person = People[PID]
                self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 5).addItem("""%s %s"""%(Person.f_Name, Person.l_Name))

            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 6, QtGui.QPushButton("Edit"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 6).uniqueId = """%d"""%Expense.SgExp_id
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 6).clicked.connect(self.OnEditEvent)
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 7, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 7).uniqueId = """%d"""%Expense.SgExp_id
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 7).clicked.connect(self.OnDeleteEvent)
      
    def OnEditEvent(self):
        SgExp_id =  int(self.sender().uniqueId)
        Expense = self.SubGroupExpenses.GetSubGroupExpenses(SgExp_id = SgExp_id)[0]
        PeopleInExpense = self.PeopeInSubGroup.GetAllPeopleInSubgroupOnEvent(SgExp_id, self.EventId)
        PIDs = []
        for PID, Prop in PeopleInExpense:
           PIDs.append(PID) 
        self.EditEventDiag = AddSubGroupExpense(self.People, Expense, PIDs)
        self.EditEventDiag.show()
        self.connect(self.EditEventDiag, QtCore.SIGNAL("accepted()"), self.EditAccepted)
        
    def EditAccepted(self):
        Expense = self.EditEventDiag.GetExpenseObj()
        self.SubGroupExpenses.UpdateSubGroupExpense(Expense)
        self.PeopeInSubGroup.RemoveSubGroup(Expense.SgExp_id)
        PeopleInGroup = self.EditEventDiag.GetPIDSOfPeopleOnEvent()
        for Person in PeopleInGroup:
            print """Adding %d : %d"""%(Expense.SgExp_id, Person[0])
            self.PeopeInSubGroup.AddPersonToSubGroup(Person[0], self.EventId, Expense.SgExp_id, Person[1])
        
        self.PopulateTable()

    def OnDeleteEvent(self, Exp_Id):
        SgExp_id =  int(self.sender().uniqueId)
        self.ConfirmDelete = ConfirmDiag("Are you sure you want to delete?")
        self.ConfirmDelete.ID = str(SgExp_id)
        self.connect(self.ConfirmDelete, QtCore.SIGNAL("accepted()"), self.DeleteExpenseAccepted)
        self.ConfirmDelete.show()
        
    def DeleteExpenseAccepted(self):
        SgExp_id = int(self.ConfirmDelete.ID)
        self.SubGroupExpenses.RemoveSubGroupExpense(SgExp_id)
        self.PeopeInSubGroup.RemoveSubGroup(SgExp_id)
        self.PopulateTable()

class AddTripExpense(QtGui.QDialog, Ui_AddTripExpenseDiag):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Result = 0
        
        self.Amount = '$0.0'
        
        self.connect(self.AddAnotherExpenseBut, QtCore.SIGNAL("clicked()"), self.Addmore)
        self.connect(self.FinishedBut, QtCore.SIGNAL("clicked()"), self.Finished)
        self.connect(self.CancelBut, QtCore.SIGNAL("clicked()"), self.Cancel)
        
        self.connect(self.ExpenseAmountEdit, QtCore.SIGNAL("editingFinished()"), self.CheckAmount)
    
    def CheckAmount(self):
        Number, FloatCheck = self.ExpenseAmountEdit.text().replace('$','').toFloat()
        if not FloatCheck:
            self.ExpenseAmountEdit.setText(self.Amount)
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Input must be of type float")
            self.Message.show()
        else:
            if '$' not in self.ExpenseAmountEdit.text():
                text = '$' + self.ExpenseAmountEdit.text()
                self.ExpenseAmountEdit.setText(text)
                self.Amount = text

    def CheckExpenseTitle(self):
        Res = False
        if self.ExpenseName.text() != "":
            Res = True
        return Res
        
        

    def Addmore(self):
        if self.CheckExpenseTitle():
            self.Result = 2
            self.accept()
        else:
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Please enter an expense name")
            self.Message.show()
            
        
    def Finished(self):
        if self.CheckExpenseTitle():
            self.Result = 1
            self.accept()
        else:
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Please enter an expense name")
            self.Message.show()
    
    def Cancel(self):
        self.Result = 0
        self.reject()
   
class ViewTripExpense(QtGui.QDialog, Ui_ViewTripExpenseDiag):
    def __init__(self, Expenses, EventId, People):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Expenses = Expenses
        self.EventId = EventId
        self.People = People
        
        self.PopulateTable()
        
    def PopulateTable(self):
        
        while(self.tableWidget.rowCount() > 0):
            self.tableWidget.removeRow(0)
        Expenses = self.Expenses.GetExpenses(EID = self.EventId)
        
        for Expense in Expenses:
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d"""%Expense.TexID))
            
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 1, QtGui.QTableWidgetItem("""%d/%d/%d"""%(Expense.Date.day, Expense.Date.month, Expense.Date.year)))
            
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 2, QtGui.QTableWidgetItem("""%s"""%Expense.Desc.split("\n\n")[0]))
            
            Person = self.People.GetPerson(PID = Expense.PID)
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 3, QtGui.QTableWidgetItem("""%s %s"""%(Person.f_Name, Person.l_Name)))

            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 4, QtGui.QTableWidgetItem("""%.2f"""%Expense.Amount))

            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 5, QtGui.QPushButton("Edit"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 5).uniqueId = """%d"""%Expense.TexID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 5).clicked.connect(self.OnEditEvent)
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 6, QtGui.QPushButton("Delete"))
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 6).uniqueId = """%d"""%Expense.TexID
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 6).clicked.connect(self.OnDeleteEvent)
      
    def OnEditEvent(self):
        button =  self.sender()
        Expense = self.Expenses.GetExpenses(TexId = int(button.uniqueId))[0]
        self.EditExpenseDiag = EditTripExpense(Expense)
        self.EditExpenseDiag.show()

        
    def OnDeleteEvent(self, Exp_Id):
        button =  self.sender()
        Expense = self.Expenses.GetExpenses(TexId = int(button.uniqueId))[0]
        self.ConfirmDelete = ConfirmDiag("Are you sure you want to delete %s?"%Expense.Desc.split("\n\n")[0])
        self.ConfirmDelete.ID = button.uniqueId
        self.connect(self.ConfirmDelete, QtCore.SIGNAL("accepted()"), self.DeleteExpenseAccepted)
        self.ConfirmDelete.show()
        
        
    def DeleteExpenseAccepted(self):
        self.Expenses.RemoveExpense(int(self.ConfirmDelete.ID))
        self.PopulateTable()
    
class EditTripExpense(QtGui.QDialog, Ui_EditTripExpenseDiag):
    def __init__(self, Expense):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Expense=Expense
        
        self.ExpenseName.setText(self.Expense.Desc.split('\n\n')[0])
        #self.Date = Date
        #self.Desc = Desc
        self.ExpenseAmountEdit.setText("""%0.2f"""%self.Expense.Amount)
        
        self.Amount = self.ExpenseAmountEdit.text()
        
        self.connect(self.FinishedBut, QtCore.SIGNAL("clicked()"), self.Finished)
        self.connect(self.CancelBut, QtCore.SIGNAL("clicked()"), self.Cancel)
        
        self.connect(self.ExpenseAmountEdit, QtCore.SIGNAL("editingFinished()"), self.CheckAmount)
    
    def CheckAmount(self):
        Number, FloatCheck = self.ExpenseAmountEdit.text().replace('$','').toFloat()
        if not FloatCheck:
            self.ExpenseAmountEdit.setText(self.Amount)
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Input must be of type float")
            self.Message.show()
        else:
            if '$' not in self.ExpenseAmountEdit.text():
                text = '$' + self.ExpenseAmountEdit.text()
                self.ExpenseAmountEdit.setText(text)
                self.Amount = text

    def CheckExpenseTitle(self):
        Res = False
        if self.ExpenseName.text() != "":
            Res = True
        return Res
   
    def Finished(self):
        if self.CheckExpenseTitle():
            self.accept()
        else:
            self.Message = QtGui.QMessageBox(self)
            self.Message.setText("Please enter an expense name")
            self.Message.show()
    
    def Cancel(self):
        self.reject()

class DatesOnEventDiag(QtGui.QDialog, Ui_EventDatesSelectDiag):
    def __init__(self, PersonDates, EventDates):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        
        
        self.PersonDates = PersonDates
        self.EventDates = EventDates
        
        self.tableWidget.resizeColumnToContents(2)
        
        self.PopulateWindow()
        
        
    def PopulateWindow(self):
        Delta = 0
        StartDate = self.EventDates[0]
        EndDate = self.EventDates[1]
        while (StartDate + datetime.timedelta(Delta)) != EndDate + datetime.timedelta(1):
            Date = (StartDate + datetime.timedelta(Delta))
            self.tableWidget.insertRow(self.tableWidget.rowCount())
            self.tableWidget.setItem(self.tableWidget.rowCount()-1, 0, QtGui.QTableWidgetItem("""%d/%d/%d"""%(Date.day, Date.month, Date.year)))
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 1, QtGui.QCheckBox())
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setTristate(False)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setCheckState(2)
            self.connect(self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1), QtCore.SIGNAL("clicked()"),self.CheckAction)
            
            self.tableWidget.setCellWidget(self.tableWidget.rowCount()-1, 2, QtGui.QSpinBox())
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setRange(0,100)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setSingleStep(25)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setValue(100)
            self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setEnabled(True)
            
            ##check on the users values.
            i = 0
            while i < len(self.PersonDates):
                if Date == self.PersonDates[i][0]:
                    self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setValue(self.PersonDates[i][1])
                    if self.PersonDates[i][1] == 0:
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setCheckState(0)
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setEnabled(False)
                    else:
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 1).setCheckState(2)
                        self.tableWidget.cellWidget(self.tableWidget.rowCount()-1, 2).setEnabled(True)
                i = i + 1
            Delta = Delta + 1
        
    
    def GetDatesPresentFromWindow(self):
        i = 0
        PersonDates = []
        while i < self.tableWidget.rowCount():
            Date = self.tableWidget.item(i,0).text().split("""/""")
            Present = self.tableWidget.cellWidget(i, 2).value()
            PersonDates.append((datetime.date(int(Date[2]), int(Date[1]), int(Date[0])),Present))    
            i = i + 1
        return PersonDates
    
    def CheckAction(self):
        i = 0
        PersonDates = []
        while i < self.tableWidget.rowCount():
            if self.tableWidget.cellWidget(i, 1).checkState() == 2:
                self.tableWidget.cellWidget(i, 2).setEnabled(True)
                self.tableWidget.cellWidget(i, 2).setValue(100)
            else:
                self.tableWidget.cellWidget(i, 2).setEnabled(False)
                self.tableWidget.cellWidget(i, 2).setValue(0)
            i = i + 1
        
class AdminCreateNewEvent(QtGui.QDialog, Ui_CreateNewEventDiag):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
  
class ManagePeopleOnEvent(QtGui.QDialog, Ui_AddPersonToEventDiag):
    def __init__(self, EventID, PeopleOnEvents, People, EventDates):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        
        self.StartDate = EventDates[0]
        self.EndDate = EventDates[1]
        
        self.PeopleOnEvents = PeopleOnEvents
        self.EventID = EventID
        self.People = People
        
        self.connect(self.AddPersonButton, QtCore.SIGNAL("clicked()"), self.AddPerson)
        self.connect(self.RemovePersonFromEventButton, QtCore.SIGNAL("clicked()"), self.DeletePerson)
        
        self.PopulateComboBox()
        
        self.PopulateList()
    
    def PopulateComboBox(self):
        self.comboBox.clear()
        Peps = self.People.GetAllPeople()
        PepsOnEvents = self.PeopleOnEvents.GetAllPeopleOnEvent(self.EventID)
        for P in Peps:
            Exists = False
            for Person in PepsOnEvents:
                if Person[0] == P.PID:
                    Exists = True
            if Exists == False:
                self.comboBox.addItem("""ID:%d  Name:%s %s"""% (P.PID, P.f_Name, P.l_Name))
            
    def PopulateList(self):
        self.PeopleIneventList.clear()
        PepsOnEvents = self.PeopleOnEvents.GetAllPeopleOnEvent(self.EventID)
        for PepOnEvent in PepsOnEvents:
            Pep = self.People.GetPerson(PID = PepOnEvent[0])
            self.PeopleIneventList.addItem("""ID:%d  Name:%s %s"""% (Pep.PID, Pep.f_Name, Pep.l_Name))
            
        
        
    def AddPerson(self):
        Exists = False
        ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
        PeopleOneEvent = self.PeopleOnEvents.GetAllPeopleOnEvent(self.EventID)
        for People in PeopleOneEvent:
            if People[0] == ID:
                Exists = True
        
        if Exists == False:
            Dates = []
            Delta = 0
            while (self.StartDate + datetime.timedelta(Delta)) != self.EndDate:
                Dates.append((self.StartDate + datetime.timedelta(Delta),100))
                Delta = Delta + 1
            Dates.append((self.StartDate + datetime.timedelta(Delta),100))
            self.PeopleOnEvents.AddPersonToEvent(ID, self.EventID, Dates)
            self.PopulateList()
            self.PopulateComboBox()
        else:
            print "Already There"
            
            
    def DeletePerson(self):
        self.ConfirmDiag = ConfirmDiag("""Are you sure you want to delete %s"""%(self.PeopleIneventList.currentItem().text()))
        self.ConfirmDiag.show()
        self.connect(self.ConfirmDiag, QtCore.SIGNAL("accepted()"), self.DeleteUserAccepted)

    def DeleteUserAccepted(self):
        ID = int(self.PeopleIneventList.currentItem().text().split(' ')[0].replace('ID:',''))
        self.emit(QtCore.SIGNAL('RemovePersonFromEvent(QString)'), str(ID))
        self.PopulateList()
        self.PopulateComboBox()
             
class AdminEditEvent(QtGui.QDialog, Ui_EditEventDiag):
    def __init__(self, Events):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.Events = Events
        
        self.PopulateComboBox()
        self.comboBox.setCurrentIndex(0)
        self.connect(self.comboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.ComboChange)
        self.connect(self.ButtonSaveChanges, QtCore.SIGNAL("clicked()"), self.SaveCurrent)
        self.connect(self.ButtonDeleteEvent, QtCore.SIGNAL("clicked()"), self.Delete)
        self.ComboChange()
        
    def PopulateComboBox(self):
        self.comboBox.clear()
        Events = self.Events.GetAllEvents()
        for E in Events:
            self.comboBox.addItem("""ID:%d  EventName:%s"""% (E.EID, E.EventName))
        
        
        
        
    def ComboChange(self):
        try:
            ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
        except:
            pass
        Event = self.Events.GetEvent(EID = ID)
        self.EventNameEdit.setText(Event.EventName)
        self.EventDescEdit.setText(Event.EventDesc)
        self.StartDateEdit.setDate( QtCore.QDate(Event.StartDate.year, Event.StartDate.month, Event.StartDate.day))
        self.EndDateEdit.setDate( QtCore.QDate(Event.EndDate.year, Event.EndDate.month, Event.EndDate.day))
        
    def SaveCurrent(self):
        ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
        StartDate = datetime.date(self.StartDateEdit.date().year(),
                                  self.StartDateEdit.date().month(),
                                  self.StartDateEdit.date().day())
        EndDate = datetime.date(self.EndDateEdit.date().year(),
                                self.EndDateEdit.date().month(),
                                self.EndDateEdit.date().day())
        
        self.Events.UpdateEvent(ID,
                                self.EventNameEdit.text(),
                                StartDate,
                                EndDate,
                                self.EventDescEdit.text())
        self.ComboChange()
        
    def Delete(self):
        self.ConfirmDiag = ConfirmDiag("""Are you sure you want to delete %s"""%(self.EventNameEdit.text()))
        self.ConfirmDiag.show()
        self.ConfirmDiag.setModal(True)
        self.connect(self.ConfirmDiag, QtCore.SIGNAL("accepted()"), self.DeleteAccepted)

    def DeleteAccepted(self):
        ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
        self.Events.RemoveEvent(ID)
        self.PopulateComboBox()
        
class AdminEditPeople(QtGui.QDialog, Ui_AdminUserDetailsDiag):
    def __init__(self, People):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.People = People
        
        self.PopulateComboBox()
        
        self.connect(self.SaveChangesButton, QtCore.SIGNAL("clicked()"), self.SaveCurrent)
        self.connect(self.comboBox, QtCore.SIGNAL("currentIndexChanged(int)"), self.ComboChange)
        self.connect(self.ButtonDeleteUser, QtCore.SIGNAL("clicked()"), self.DeleteUser)
    
    def DeleteUser(self):
        self.ConfirmDiag = ConfirmDiag("""Are you sure you want to delete %s %s"""%(self.LineEditFirstName.text(), self.LineEditSecondName.text()))
        self.ConfirmDiag.show()
        self.connect(self.ConfirmDiag, QtCore.SIGNAL("accepted()"), self.DeleteUserAccepted)

    def DeleteUserAccepted(self):
        ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
        self.People.RemovePerson(ID)
        #self.PopulateComboBox()
        
        
    def ComboChange(self):
        if self.comboBox.currentText() == "New User":
            self.LineEditId.setText('')
            self.LineEditFirstName.setText('')
            self.LineEditSecondName.setText('')
            self.LineEditUserName.setText('')
            self.checkBox.setCheckState(False)
        else:
            ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
            Person = self.People.GetPerson(PID = ID)
            self.LineEditId.setText(str(Person.PID))
            self.LineEditFirstName.setText(Person.f_Name)
            self.LineEditSecondName.setText(Person.l_Name)
            self.LineEditUserName.setText(Person.UserName)
            if Person.Admin:
                self.checkBox.setCheckState(True)
                self.checkBox.setTristate(False)
            else:
                self.checkBox.setCheckState(False)
        
    
    def SaveCurrent(self):
        if self.comboBox.currentText() == "New User":
            self.People.AddPerson(self.LineEditFirstName.text(), self.LineEditSecondName.text(),
                                  self.LineEditUserName.text())
            if self.checkBox.checkState():
                Person = self.People.GetPerson(f_name=self.LineEditFirstName.text(),
                                           l_name = self.LineEditSecondName.text(),
                                           UserName = self.LineEditUserName.text())
                Person.Admin = True
                self.People.UpdatePerson(Person)
            
            
        else:
            ID = int(self.comboBox.currentText().split(' ')[0].replace('ID:',''))
            Person = self.People.GetPerson(PID = ID)
            Person.f_Name = self.LineEditFirstName.text()
            Person.l_Name = self.LineEditSecondName.text()
            Person.UserName = self.LineEditUserName.text()
            if self.checkBox.checkState():
                Person.Admin = True
            else:
                Person.Admin = False
            
            self.People.UpdatePerson(Person)
        #self.PopulateComboBox()
        
    
    def PopulateComboBox(self):
        self.comboBox.clear()
        self.comboBox.addItem("New User")
        Peps = self.People.GetAllPeople()
        for P in Peps:
            self.comboBox.addItem("""ID:%d  Name:%s %s"""% (P.PID, P.f_Name, P.l_Name))
        
class SignIn(QtGui.QDialog, Ui_SignInDiag):
    def __init__(self):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        
class ModifyDetails(QtGui.QDialog, Ui_UserDetailsDiag):
    def __init__(self, ID, f_Name,l_Name,UserName):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.LineEditId.setText(str(ID))
        self.LineEditFirstName.setText(f_Name)
        self.LineEditSecondName.setText(l_Name)
        self.LineEditUserName.setText(UserName)

class ViewExpenseSummary(QtGui.QDialog, Ui_ViewExpenseSummaryDiag):
    def __init__(self, TripExpenses, PeopleOnEvents, SubGroupExpenses, PeopleInSubGroups, People):
        QtGui.QDialog.__init__(self)
        self.setupUi(self)
        self.TripExpenses = TripExpenses
        self.PeopleOnEvents = PeopleOnEvents
        self.SubGroupExpenses = SubGroupExpenses
        self.PeopleInSubGroups = PeopleInSubGroups
        self.People = People
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
      
        
class TripExpensesMainWindow(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)    
        self.setupUi(self)
        
        ##Setup the connection with the MYSQL Database
        self.Database = DataBase.Database()
        self.SQL = MySQL.Connection()
        self.People = People.People(self.SQL)
        self.Events = Events.Events(self.SQL)
        self.PeopleOnEvents = PeopleOnEvents.PeopleEvents(self.SQL)
        self.TripExpenses = TripExpenses.Expenses(self.SQL)
        self.SubGroupExpenses = SubGroupExpenses.SubGroupExpenses(self.SQL)
        self.PeopleInSubGroups = PeopleInSubGroup.PeopleInSubGroup(self.SQL)
        
        ##This is the Person object of the person that signed in.
        self.PID = -1
        self.Admin = False
        
        self.EventId = -1
        
        self.SignInStart()
        
        self.InitActions()
        
        
        self.Timer = QtCore.QTimer()
        self.Timer.setInterval(10000) 
        self.Timer.setSingleShot(True)
        QtCore.QObject.connect(self.Timer, QtCore.SIGNAL("timeout()"), self.PopulateMainWindowSpread)
        
    def InitActions(self):
        self.connect(self.actionModify_Details, QtCore.SIGNAL("triggered()"), self.ActionModifyPersonalDetails)
        self.connect(self.actionAdd_Person,QtCore.SIGNAL("triggered()"), self.ActionAddNewPerson)
        self.connect(self.actionManage_People_On_Event,QtCore.SIGNAL("triggered()"), self.ActionManagePeopleOnEvent)
        self.connect(self.actionEdit_Dates_On_Event,QtCore.SIGNAL("triggered()"), self.ActionEditDateOnEvent)
        self.connect(self.actionAdd_Expenses,QtCore.SIGNAL("triggered()"), self.ActionAddTripExpenseEvent)
        self.connect(self.actionView_Expenses,QtCore.SIGNAL("triggered()"), self.ActionViewTripExpense)
        self.connect(self.actionAdd_Subgroup_Expense, QtCore.SIGNAL("triggered()"), self.ActionAddSubgroupExpense)
        self.connect(self.actionView_Subgroup_Expenses, QtCore.SIGNAL("triggered()"), self.ActionViewSubgroupExpense)
        self.connect(self.actionView_Expense_Summary, QtCore.SIGNAL("triggered()"), self.ActionViewExpenseSummary)
        
    def AdminDeActivate(self):
        self.actionEdit_People.setEnabled(False)
        self.actionEdit_Event.setEnabled(False)
        #del(self.actionEdit_People)
        
    def AdminActivate(self):
        self.actionEdit_People.setEnabled(True)
        self.connect(self.actionEdit_People, QtCore.SIGNAL("triggered()"), self.ActionEdit_People)
        #self.connect(self.actionAdd_Event, QtCore.SIGNAL("triggered()"), self.ActionAdd_Event)
        self.connect(self.actionEdit_Event, QtCore.SIGNAL("triggered()"), self.ActionEdit_Events)
        
    def Exit(self):
        self.close()
        
    def SignInStart(self):
        self.SigninDiag = SignIn()
        self.SigninDiag.show()
        self.connect(self.SigninDiag, QtCore.SIGNAL("accepted()"), self.SignInNameEntered)
        self.connect(self.SigninDiag, QtCore.SIGNAL("rejected()"), self.Exit)
    
    def SignInNameEntered(self):
        UsrName = self.SigninDiag.NameEdit.text()
        if UsrName == '':
            self.SignInStart()
        else:
            Person = self.People.GetPerson(UserName = UsrName)
            if Person != None:
                self.PID = Person.PID
                self.Admin = Person.Admin
                self.SignInSelectEvent()
            else:
                print "Fail"
                self.SignInStart()
                      
    def SignInSelectEvent(self):
        if self.Admin:
            self.AdminActivate()
            Events = self.Events.GetAllEvents()
            EventsList = []
            for Event in Events:
                EventsList.append("""ID:%d  EventName:%s"""% (Event.EID, Event.EventName))
                
            self.SelectEventDiag = SelectEventAdmin(EventsList)
            self.connect(self.SelectEventDiag, QtCore.SIGNAL("NewEvent()"), self.ActionAdd_Event)
        else:
            self.AdminDeActivate()
            
            Events = self.PeopleOnEvents.GetAllEventsPersonOn(self.PID)
            EventsList = []
            for Event in Events:
                EvID = Event[0]
                print EvID
                EventInfo = self.Events.GetEvent(EID = EvID)
                EventsList.append("""ID:%d  EventName:%s"""% (EventInfo.EID, EventInfo.EventName))
        
                self.SelectEventDiag = SelectEvent(EventsList)
        
        self.SelectEventDiag.show()
        
        self.connect(self.SelectEventDiag, QtCore.SIGNAL("accepted()"), self.SignInEventEntered)
        self.connect(self.SelectEventDiag, QtCore.SIGNAL("rejected()"), self.Exit)
                
    def SignInEventEntered(self):
        self.EventId = int(self.SelectEventDiag.listWidget.currentItem().text().split(' ')[0].replace('ID:',''))
        self.PopulateMainWindow()
        
    def ActionModifyPersonalDetails(self):
        print self.PID
        Person = self.People.GetPerson(PID = self.PID)
        if Person != None:
            self.UserDetailsDiag = ModifyDetails(Person.PID, Person.f_Name, Person.l_Name, Person.UserName)
            self.UserDetailsDiag.show()
            self.connect(self.UserDetailsDiag, QtCore.SIGNAL("accepted()"), self.ModifyPersonalDetailsAccept)
    
    def ModifyPersonalDetailsAccept(self):
        Person = self.People.GetPerson(PID = self.PID)
        Person.f_Name = self.UserDetailsDiag.LineEditFirstName.text()
        Person.l_Name = self.UserDetailsDiag.LineEditSecondName.text()
        Person.UserName = self.UserDetailsDiag.LineEditUserName.text()
        self.People.UpdatePerson(Person)
        
    def ActionAddNewPerson(self):
        self.AddNewPersonDiag = AddNewPerson()
        self.AddNewPersonDiag.show()
        self.connect(self.AddNewPersonDiag, QtCore.SIGNAL("accepted()"), self.AddNewPersonAccept)
        
    def AddNewPersonAccept(self):
        print "Accepted"
        
    def ActionAdd_Event(self):
        self.AddEventDiag = AdminCreateNewEvent()
        self.AddEventDiag.show()
        self.connect(self.AddEventDiag, QtCore.SIGNAL("accepted()"), self.ActionAdd_EventAccept)
        
    def ActionAdd_EventAccept(self):
        StartDate = datetime.date(self.AddEventDiag.StartDateEdit.date().year(),
                                  self.AddEventDiag.StartDateEdit.date().month(),
                                  self.AddEventDiag.StartDateEdit.date().day())
        EndDate = datetime.date(self.AddEventDiag.EndDateEdit.date().year(),
                                self.AddEventDiag.EndDateEdit.date().month(),
                                self.AddEventDiag.EndDateEdit.date().day())
        self.Events.AddEvent(self.AddEventDiag.EventNameEdit.text(),
                             StartDate,
                             EndDate,
                             self.AddEventDiag.EventDescEdit.text())
        self.SignInSelectEvent()
        
    def ActionEdit_People(self):
        self.EditPeopleDiag = AdminEditPeople(self.People)
        self.EditPeopleDiag.show()
        
    def ActionEdit_Events(self):
        self.EditEventsDiag = AdminEditEvent(self.Events)
        self.EditEventsDiag.show()
        
    def ActionManagePeopleOnEvent(self):
        Event = self.Events.GetEvent(self.EventId)
        EventDates = [Event.StartDate, Event.EndDate]
        self.ManagePeopleOnEventDiag = ManagePeopleOnEvent(self.EventId, self.PeopleOnEvents, self.People, EventDates)
        self.ManagePeopleOnEventDiag.show()
        self.connect(self.ManagePeopleOnEventDiag,QtCore.SIGNAL('RemovePersonFromEvent(QString)'), self.RemovePersonFromEvent)
        
    def RemovePersonFromEvent(self, ID):
        ID = int(ID)
        self.PeopleOnEvents.RemovePersonFromEvent(self.EventId, ID)
        Expenses = self.TripExpenses.GetExpenses(EID=self.EventId, PID = ID)
        if Expenses != None:
            for Exp in Expenses:
                self.TripExpenses.RemoveExpense(Exp.TexID)
  
    def ActionEditDateOnEvent(self):
        Person = self.People.GetPerson(PID = self.PID)
        PersonDates = self.PeopleOnEvents.GetDatesPersonOnEvent(self.EventId, self.PID)
        Event = self.Events.GetEvent(self.EventId)
        EventDates = [Event.StartDate, Event.EndDate]
        self.EditDatesOnEventDiag = DatesOnEventDiag(PersonDates, EventDates)
        self.EditDatesOnEventDiag.show()
        
        self.connect( self.EditDatesOnEventDiag, QtCore.SIGNAL("accepted()"), self.ActionAcceptedEditDateOnEvent)
        
    def ActionAcceptedEditDateOnEvent(self):
        self.PeopleOnEvents.UpdateEventPeople(self.EventId,
                                              self.PID,
                                              self.EditDatesOnEventDiag.GetDatesPresentFromWindow())
        
    def ActionAddTripExpenseEvent(self):
        self.AddTripExpenseDiag = AddTripExpense()
        self.AddTripExpenseDiag.show()
        self.connect(self.AddTripExpenseDiag, QtCore.SIGNAL("accepted()"), self.ActionAcceptedAddTripExpenseEvent)
    
    def ActionAcceptedAddTripExpenseEvent(self):
        Result = self.AddTripExpenseDiag.Result
        ExpenseName = self.AddTripExpenseDiag.ExpenseName.text()
        ExpenseDesc = ExpenseName + """\n\n""" + self.AddTripExpenseDiag.ExpenseDesc.toPlainText()
        Amount = float(self.AddTripExpenseDiag.ExpenseAmountEdit.text().replace('$',''))
        Date = datetime.date(self.AddTripExpenseDiag.ExpenseDateEdit.date().year(),
                                  self.AddTripExpenseDiag.ExpenseDateEdit.date().month(),
                                  self.AddTripExpenseDiag.ExpenseDateEdit.date().day())
        self.TripExpenses.AddExpense(self.EventId, self.PID, Date, ExpenseDesc, Amount)
                             
        if Result == 2:
            self.ActionAddTripExpenseEvent()
  
    def ActionViewTripExpense(self):
        self.VeiwTripExpensesDiag = ViewTripExpense(self.TripExpenses, self.EventId, self.People)
        self.VeiwTripExpensesDiag.show()
        
    def ActionAddSubgroupExpense(self):
        PIDsOnEvent = self.PeopleOnEvents.GetAllPeopleOnEvent(self.EventId)
        People = self.People.GetAllPeopleDict()
        PeopleOnEvent = {}
        for PID, Date in PIDsOnEvent:
            PeopleOnEvent[PID] = People[PID]
        self.AddSubGroupExpenseDiag = AddSubGroupExpense(PeopleOnEvent)
        self.AddSubGroupExpenseDiag.show()
        self.connect(self.AddSubGroupExpenseDiag,QtCore.SIGNAL("accepted()"), self.ActionAcceptedAddSubGroupExpense)
        
    def ActionAcceptedAddSubGroupExpense(self):
        ExpAmount = self.AddSubGroupExpenseDiag.getAmount()
        ExpDate = self.AddSubGroupExpenseDiag.getDate()
        ExpDesc = self.AddSubGroupExpenseDiag.getDesc()
        self.SubGroupExpenses.AddSubGroupExpense(self.EventId, self.PID, ExpDate, ExpDesc, ExpAmount)
        
        Expense = self.SubGroupExpenses.GetSubGroupExpenses(EID=self.EventId, PID = self.PID, Exp_Discription = ExpDesc, Exp_Date = ExpDate)[0]
        PeopleInGroup = self.AddSubGroupExpenseDiag.GetPIDSOfPeopleOnEvent()
        for Person in PeopleInGroup:
            print """Adding %d : %d"""%(Expense.SgExp_id, Person[0])
            self.PeopleInSubGroups.AddPersonToSubGroup(Person[0], self.EventId, Expense.SgExp_id, Person[1])
        
    
    def ActionViewSubgroupExpense(self):
        PIDsOnEvent = self.PeopleOnEvents.GetAllPeopleOnEvent(self.EventId)
        People = self.People.GetAllPeopleDict()
        PeopleOnEvent = {}
        for PID, Date in PIDsOnEvent:
            PeopleOnEvent[PID] = People[PID]
        self.ViewSubGroupExpenseDiag = ViewSubGroupExpense(self.SubGroupExpenses, self.PeopleInSubGroups, PeopleOnEvent, self.EventId)
        self.ViewSubGroupExpenseDiag.show()
            
    def ActionViewExpenseSummary(self):
        PIDsOnEvent = self.PeopleOnEvents.GetAllPeopleOnEvent(self.EventId)
        People = self.People.GetAllPeopleDict()
        PeopleOnEvent = {}
        for PID, Date in PIDsOnEvent:
            PeopleOnEvent[PID] = People[PID]
        
        self.ViewExpenseSummaryDiag = ViewExpenseSummary(self.TripExpenses, self.PeopleOnEvents, self.SubGroupExpenses, self.PeopleInSubGroups, self.People)
        self.ViewExpenseSummaryDiag.show()
            
        
    def PopulateMainWindow(self):
        EventInfo = self.Events.GetEvent(EID = self.EventId)
        self.EventNameDisp.setText(EventInfo.EventName)
        self.StartDateDisp.setText("""%d/%d/%d"""%(EventInfo.StartDate.day,EventInfo.StartDate.month,EventInfo.StartDate.year))
        self.EndDateDisp.setText("""%d/%d/%d"""%(EventInfo.EndDate.day,EventInfo.EndDate.month,EventInfo.EndDate.year))
        
        self.PopulateMainWindowSpread()
         
    def PopulateMainWindowSpread(self):
        print 'tick'
        self.GetDataThread = GetMainDataThread(self.People, self.Events, self.PeopleOnEvents,
                                               self.TripExpenses, self.SubGroupExpenses, self.EventId)
        self.connect(self.GetDataThread, QtCore.SIGNAL("update(PyQt_PyObject)"), self.PopulateMainWindowSpreadDataRec)
        self.GetDataThread.start()
    
    def PopulateMainWindowSpreadDataRec(self, Data):
        while(self.MainPagetable.rowCount() > 0):
            self.MainPagetable.removeRow(0)
        for Line in Data:
            self.MainPagetable.insertRow(self.MainPagetable.rowCount())
            i = 0
            while i < len(Line):
                self.MainPagetable.setItem(self.MainPagetable.rowCount()-1, i, QtGui.QTableWidgetItem("""%s"""%Line[i]))
                i = i + 1
        i = 0
        while (i < self.MainPagetable.columnCount()):
            self.MainPagetable.resizeColumnToContents(i)
            i = i + 1
        self.Timer.start()

class GetMainDataThread(QtCore.QThread):
    def __init__(self, People, Events, PeopleOnEvents, TripExpenses, SubGroupExpenses, EventId):
        QtCore.QThread.__init__(self)
        self.People = People
        self.Events = Events
        self.PeopleOnEvents = PeopleOnEvents
        self.TripExpenses = TripExpenses
        self.EventId = EventId
        self.SubGroupExpenses = SubGroupExpenses
        
        
    def run(self):
        PeopleOnEvent = self.PeopleOnEvents.GetAllPeopleOnEvent(self.EventId)
        TotalManDays =  self.PeopleOnEvents.GetTotalEventManDays(self.EventId)
        TotalEventCost = self.TripExpenses.GetTotalEventCost(self.EventId)
        People = self.People.GetAllPeopleDict()
        Data = []
        for PID, Dates in PeopleOnEvent:
            Line = []
            Person = People[PID]
            Person = self.People.GetPerson(PID = PID)
            Line.append("""%s %s"""%(Person.f_Name, Person.l_Name))
            
            AmountSpentByPerson = self.TripExpenses.GetTotalSpentByPersonOnEvent(PID, self.EventId)
            Line.append("""$%.2f"""%round(AmountSpentByPerson,2))
            
            PersonsManDays = self.PeopleOnEvents.GetPersonsManDays(Dates = Dates)
            Line.append("""$%.2f"""%round(float((PersonsManDays/TotalManDays)*TotalEventCost),2))
            
            AmountSpentByPerson = self.SubGroupExpenses.GetTotalSpentByPersonOnSubGroups(PID, self.EventId)
            Line.append("""$%.2f"""%round(AmountSpentByPerson,2))
            
            Data.append(Line)
            
            
        
        self.emit( QtCore.SIGNAL('update(PyQt_PyObject)'), Data)
        return


    
        
        
app = QtGui.QApplication(sys.argv)
form = TripExpensesMainWindow()
form.show()
app.exec_()